<template>
  <div class="chat-window">
    <!-- 未登录提示 -->
    <div v-if="!userStore.isLoggedIn" class="login-tip">
      <van-empty
        class="custom-empty"
        image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
        :description="'请先登录'"
      >
        <van-button
          round
          type="primary"
          class="login-btn"
          @click="router.push('/login')"
        >
          去登录
        </van-button>
      </van-empty>
    </div>

    <!-- 聊天内容 -->
    <template v-else>
      <div class="chat-container" ref="messageListRef">
        <div class="messages">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message-item', message.role]"
          >
            <template v-if="message.role === 'assistant' || message.role === 'other'">
              <van-image
                round
                width="40"
                height="40"
                :src="otherAvatar"
                class="avatar"
              />
            </template>
            <div class="message-content">
              <div class="message-bubble" v-html="formatMessage(message.content)">
              </div>
              <div v-if="loading && index === messages.length - 1" class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
            <template v-if="message.role === 'user'">
              <van-image
                round
                width="40"
                height="40"
                :src="userStore.userInfo?.avatar"
                class="avatar"
              />
            </template>
          </div>
        </div>
      </div>

      <div class="input-panel">
        <van-field
          v-model="inputMessage"
          class="message-input"
          :border="false"
          :autosize="{ minHeight: 20, maxHeight: 100 }"
          type="textarea"
          :placeholder="placeholder"
          @keypress.enter.prevent="handleSend"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :loading="loading"
              :disabled="!inputMessage.trim() || loading"
              @click="handleSend"
            >
              {{ loading ? '思考中...' : '发送' }}
            </van-button>
          </template>
        </van-field>
      </div>

      <van-overlay :show="loading" class="loading-overlay">
        <div class="loading-content">
          <van-loading type="spinner" color="#1989fa" size="24px" />
          <span class="loading-text">AI思考中...</span>
        </div>
      </van-overlay>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const props = defineProps<{
  otherAvatar: string
  placeholder?: string
  isAI?: boolean
}>()

const emit = defineEmits<{
  (e: 'send', message: string): void
}>()

const userStore = useUserStore()
const messageListRef = ref<HTMLElement>()
const inputMessage = ref('')
const loading = ref(false)
const messages = ref<Array<{ role: 'user' | 'assistant' | 'other'; content: string }>>([])

// 格式化消息（支持 Markdown）
const formatMessage = (content: string) => {
  if (props.isAI) {
    const html = marked(content)
    return DOMPurify.sanitize(html)
  }
  return content
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

// 处理消息发送
const handleSend = async () => {
  const message = inputMessage.value.trim()
  if (!message || loading.value) return

  emit('send', message)
  inputMessage.value = ''
  await scrollToBottom()
}

// 添加消息
const addMessage = (role: 'user' | 'assistant' | 'other', content: string) => {
  messages.value.push({ role, content })
  scrollToBottom()
}

// 设置加载状态
const setLoading = (value: boolean) => {
  loading.value = value
}

// 监听消息变化自动滚动
watch(messages, () => {
  scrollToBottom()
})

onMounted(() => {
  scrollToBottom()
})

// 暴露方法和属性给父组件
defineExpose({
  addMessage,
  setLoading,
  messages,
})
</script>

<style lang="less" scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect fill="%23ffffff10" width="100" height="100"/><path d="M0 0h100v100H0z" fill="none" stroke="%23ffffff20" stroke-width="0.5"/></svg>') repeat;
    background-size: 20px 20px;
    opacity: 0.5;
    pointer-events: none;
  }

  .chat-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    scroll-behavior: smooth;
    position: relative;
    z-index: 1;

    .messages {
      .message-item {
        display: flex;
        margin-bottom: 24px;
        animation: messageIn 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        perspective: 1000px;

        &.assistant, &.other {
          padding-right: 60px;

          .message-bubble {
            transform-origin: left center;
          }
        }

        &.user {
          flex-direction: row-reverse;
          padding-left: 60px;

          .message-bubble {
            transform-origin: right center;
          }
        }

        .avatar {
          flex-shrink: 0;
          margin: 0 12px;
          border: 2px solid #fff;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          transition: transform 0.3s ease;

          &:hover {
            transform: scale(1.1) rotate(5deg);
          }
        }

        .message-content {
          flex: 1;
          max-width: 80%;

          .message-bubble {
            padding: 12px 16px;
            border-radius: 16px;
            font-size: 15px;
            line-height: 1.5;
            word-break: break-word;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
            }

            :deep(pre) {
              background: #1a1a1a;
              color: #fff;
              padding: 16px;
              border-radius: 8px;
              margin: 12px 0;
              overflow-x: auto;
              box-shadow: inset 0 2px 6px rgba(0, 0, 0, 0.2);

              code {
                font-family: 'Fira Code', monospace;
                font-size: 14px;
                text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
              }
            }

            :deep(code) {
              background: #2d2d2d;
              color: #e96900;
              padding: 2px 6px;
              border-radius: 4px;
              font-size: 14px;
              font-family: 'Fira Code', monospace;
            }

            :deep(p) {
              margin: 8px 0;
              &:first-child { margin-top: 0; }
              &:last-child { margin-bottom: 0; }
            }
          }
        }

        &.user .message-bubble {
          background: linear-gradient(135deg, #95ec69 0%, #7ed321 100%);
          color: #fff;
          text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }

  .input-panel {
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    border-top: 1px solid rgba(255, 255, 255, 0.3);
    padding: 12px 16px;
    position: sticky;
    bottom: 0;
    z-index: 2;

    .message-input {
      background: rgba(255, 255, 255, 0.8);
      border-radius: 12px;
      overflow: hidden;
      transition: all 0.3s ease;

      &:focus-within {
        box-shadow: 0 0 0 2px rgba(25, 137, 250, 0.2);
      }

      :deep(.van-field__body) {
        display: flex;
        align-items: flex-end;
      }

      :deep(.van-button) {
        margin-left: 8px;
        height: 36px;
        background: linear-gradient(135deg, #1989fa 0%, #0960bd 100%);
        border: none;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.95);
        }

        &--disabled {
          opacity: 0.7;
          background: linear-gradient(135deg, #999 0%, #666 100%);
        }
      }
    }
  }

  .typing-indicator {
    display: flex;
    gap: 4px;
    padding: 8px 12px;
    margin-top: 4px;
    background: rgba(0, 0, 0, 0.05);
    border-radius: 10px;
    width: fit-content;

    span {
      width: 6px;
      height: 6px;
      background: #90939980;
      border-radius: 50%;
      animation: bounce 1.4s infinite ease-in-out;

      &:nth-child(1) { animation-delay: -0.32s; }
      &:nth-child(2) { animation-delay: -0.16s; }
    }
  }

  .loading-overlay {
    backdrop-filter: blur(5px);

    .loading-content {
      background: rgba(255, 255, 255, 0.95);
      padding: 20px 24px;
      border-radius: 16px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.2);
      animation: pulse 2s infinite;

      .loading-text {
        margin-top: 12px;
        color: #333;
        font-weight: 500;
      }
    }
  }

  // 添加未登录提示样式
  .login-tip {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);

    .custom-empty {
      padding: 32px;
      background: rgba(255, 255, 255, 0.9);
      backdrop-filter: blur(10px);
      border-radius: 16px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.2);

      :deep(.van-empty__image) {
        width: 120px;
        height: 120px;
      }

      :deep(.van-empty__description) {
        color: #666;
        font-size: 16px;
        margin: 16px 0;
      }

      .login-btn {
        width: 120px;
        height: 40px;
        background: linear-gradient(135deg, #1989fa 0%, #0960bd 100%);
        border: none;
        font-size: 16px;
        font-weight: 500;
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.95);
        }
      }
    }
  }
}

@keyframes messageIn {
  from {
    opacity: 0;
    transform: translateY(20px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

// 自定义滚动条
.chat-container {
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;

    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}
</style>
